<template>
    <div>
        <el-dialog v-model="show" title="选择用户" top="5vh" destroy-on-close draggable :close-on-click-modal="false"
            @close="handleClose" :class="{ multiple }">
            <!-- 添加分割容器 -->
            <splitpanes class="user-select-split">
                <!-- 左侧部门树 -->
                <pane min-size="20" :size="25">
                    <div class="tree-container">
                        <el-input v-model="deptName" placeholder="搜索部门" clearable prefix-icon="Search"
                            style="margin-bottom: 15px" />
                        <el-tree ref="deptTreeRef" :data="deptOptions" :props="{ label: 'name', children: 'children' }"
                            :expand-on-click-node="false" :filter-node-method="filterNode" node-key="id"
                            highlight-current default-expand-all @node-click="handleNodeClick" />
                    </div>
                </pane>

                <!-- 右侧用户列表 -->
                <pane>
                    <div class="user-list-container">
                        <el-form :model="queryParams" :inline="true" @submit.prevent>
                            <el-form-item label="用户名" prop="userName">
                                <el-input v-model="queryParams.userName" style="width: 180px" placeholder="请输入用户名"
                                    clearable @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                            </el-form-item>
                        </el-form>
                        <el-table ref="userTableRef" row-key="id" v-loading="loading" :data="userList"
                            @selection-change="handleSelectionChange" @row-click="handleRowClick" highlight-current-row>
                            <el-table-column type="selection" width="55" align="center" reserve-selection />
                            <el-table-column label="用户名" prop="userName" :show-overflow-tooltip="true" />
                            <el-table-column label="用户昵称" prop="nickName" />
                            <el-table-column label="手机号码" prop="mobile" :show-overflow-tooltip="true" />
                            <el-table-column label="所属部门" prop="department.name" :show-overflow-tooltip="true" />
                        </el-table>

                        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
                            v-model:limit="queryParams.pageSize" @pagination="getList" />
                    </div>
                </pane>
                <pane v-if="multiple" :size="20" min-size="15">
                    <div class="selected-pane">
                        <el-table :data="selectedUsers" height="100%">
                            <el-table-column prop="userName" label="已选用户" :show-overflow-tooltip="true" />
                            <el-table-column width="40">
                                <template #default="{ row }">
                                    <el-button type="danger" link @click="handleDeselect(row)" icon="delete">
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </pane>
            </splitpanes>
            <template #footer>
                <el-button @click="show = false">取消</el-button>
                <el-button type="primary" @click="handleConfirm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>



<script setup>
import { ref, reactive, defineModel, defineEmits, watch } from 'vue'
import { treeDeptList } from '@/api/system/dept'
import { listUser } from '@/api/system/user'

const emit = defineEmits(['select'])
const { multiple, data } = defineProps({
    multiple: { type: Boolean, default: false },
    data: { type: [Array, Object], default: () => [] } // 修正默认值为函数返回
})


// 统一使用 show 控制显示（与defineModel配合）
const show = ref(false)
const selectedUsers = ref([])
const userTableRef = ref()
const deptTreeRef = ref();

// 暴露打开方法
const open = () => {
    show.value = true
    initData()
}
defineExpose({ open })

// 部门树相关
const deptName = ref('')
const deptOptions = ref([])
const loading = ref(false)
const total = ref(0)

// 查询参数
const queryParams = reactive({
    pageIndex: 1,
    pageSize: 10,
    deptId: undefined,
    leafDept: true,
    userName: undefined
})

// 用户列表
const userList = ref([])

// 初始化数据
const initData = async () => {
    await getDeptTree()
    await getList()

    // 处理对象类型数据
    const initialData = Array.isArray(data) ? data : [data]
    initialData.forEach(u => {
        if (u && u.id) { // 添加有效性判断
            userTableRef.value.toggleRowSelection(u, true)
        }
    })
    //默认选中第一个部门

}

// 获取部门树
const getDeptTree = async () => {
    const res = await treeDeptList({ isActive: true })
    deptOptions.value = res
    if (res.length > 0) {
        queryParams.deptId = res[0].id
        // 高亮部门树节点
        nextTick(() => {
            deptTreeRef.value.setCurrentKey(res[0].id)
        })
    }
}

// 获取用户列表
const getList = async () => {
    loading.value = true
    try {
        const { result, totalNum } = await listUser(queryParams)
        userList.value = result
        total.value = totalNum
    } finally {
        loading.value = false
    }
}

// 部门树过滤
const filterNode = (value, data) => {
    if (!value) return true
    return data.name.includes(value)
}

const handleConfirm = () => {
    emit('select', ...selectedUsers.value)
    show.value = false
}

const handleClose = () => {
    selectedUsers.value = []
}

const handleSelectionChange = (selection) => {
    selectedUsers.value = selection
}

const handleNodeClick = (data) => {
    queryParams.deptId = data.id
    getList()
}

const handleQuery = () => {
    queryParams.pageIndex = 1
    getList()
}

const handleRowClick = (row) => {
    if (!multiple) userTableRef.value.clearSelection()  // 单选模式下，点击行时清除其他选中行
    // 切换行选中状态
    userTableRef.value.toggleRowSelection(row)
}
const resetQuery = () => {
    queryParams.userName = undefined
    getList()
}

const handleDeselect = (row) => {
    selectedUsers.value = selectedUsers.value.filter(user => user.id !== row.id)
    userTableRef.value.toggleRowSelection(row, false)
}
</script>


<style scoped lang="scss">
/* 添加分割线样式 */
.user-select-split {
    height: 60vh;

    // 分割线样式
    :deep(.splitpanes__splitter) {
        width: 3px;
        background: var(--el-border-color);
        transition: background-color 0.3s ease;

        &:hover {
            box-shadow: 0 0 4px rgba(64, 158, 255, 0.2);
        }
    }

    // 面板统一背景
    .splitpanes__pane {
        background: var(--el-bg-color);
        transition: background-color 0.3s ease;
        background: var(--el-fill-color-light);
    }
}




.tree-container {
    padding: 15px;
    height: 100%;
    overflow-y: auto;
}

.selected-pane {
    padding: 15px;
    height: 100%;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-content: flex-start;
}

.user-list-container {
    padding: 15px;
}


// 修复后：
:deep(.el-dialog) {
    &.multiple {
        --el-dialog-width: 60% !important;
        width: var(--el-dialog-width) !important;
        max-width: none;
    }
}
</style>